﻿using System;
using System.Web.Mvc;
using mvcForum.Core;
using mvcForum.Core.Specifications;
using mvcForum.Core.Interfaces.Data;
using mvcForum.Core.Interfaces.Services;

namespace mvcForum.Web.Filters {

	public class LastVisitedFilterAttribute : ActionFilterAttribute {

		public override void OnResultExecuted(ResultExecutedContext filterContext) {
			base.OnResultExecuted(filterContext);

			IContext context = DependencyResolver.Current.GetService<IContext>();

			try {
				if (filterContext.Controller != null) {
					// Is this authenticated request?
					if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated) {
						try {
							// Yes!
							IRepository<ForumUser> fuRepo = DependencyResolver.Current.GetService<IRepository<ForumUser>>();
							// Get the ForumUser equivalent of the authenticated user!
							ForumUser fu = fuRepo.ReadOne(new ForumUserSpecifications.SpecificUsername(filterContext.RequestContext.HttpContext.User.Identity.Name));
							// Got one?
							if (fu != null) {
								// Update last visited and last IP on the active user!
								fu.LastVisit = DateTime.UtcNow;
								fu.LastIP = filterContext.RequestContext.HttpContext.Request.UserHostAddress;
								// Commit changes!
								context.SaveChanges();
							}
						}
						catch (Exception ex) {
							DependencyResolver.Current.GetService<ILogger>().Log(EventType.Error, "OnResultExecuted failed.", ex);
						}
					}
				}
			}
			finally {
				// We're done, time to dispose of the unit of work!
				context.Dispose();
			}
		}
	}
}